package sunyu.view;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.servlet.view.document.AbstractXlsxStreamingView;
import sunyu.toolkit.core.NumberKit;
import sunyu.toolkit.core.TimeKit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 孙宇
 */
public class ExcelView extends AbstractXlsxStreamingView {

    @Override
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = URLEncoder.encode("数据列表.xlsx", "UTF-8");

        response.setHeader("Content-Disposition", "attachment; filename='" + fileName + "'");

        List<Map> list = (List<Map>) model.get("list");

        Sheet sheet = workbook.createSheet("数据列表");

        int i = 0;
        Row header = sheet.createRow(i);
        header.createCell(i++).setCellValue("编号");
        header.createCell(i++).setCellValue("姓名");
        header.createCell(i++).setCellValue("工资");
        header.createCell(i++).setCellValue("发工资时间");

        int rowCount = 1;
        for (Map d : list) {
            i = 0;
            Row courseRow = sheet.createRow(rowCount++);
            courseRow.createCell(i++).setCellValue(String.valueOf(d.get("id")));
            courseRow.createCell(i++).setCellValue(String.valueOf(d.get("name")));
            courseRow.createCell(i++).setCellValue(NumberKit.toDouble(String.valueOf(d.get("gz"))));
            courseRow.createCell(i++).setCellValue(TimeKit.format("yyyy-MM-dd HH:mm:ss", (Date) d.get("day")));
        }
    }
}
